package de.blitzcoder.cddatabase.gui.datatable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

/**
 *
 * @author blitzcoder
 */
public class DataTableModel implements TableModel {

    private ArrayList<DataTableRow> rows;
    private LinkedList<TableModelListener> modelListenerList;
    private final String[] columns;

    public DataTableModel(String[] columns) {
        rows = new ArrayList<DataTableRow>();
        modelListenerList = new LinkedList<TableModelListener>();
        this.columns = columns;
    }

    public void addRows(DataTableRow[] rows) {
        this.rows.addAll(Arrays.asList(rows));
        fireEvent(new TableModelEvent(this, getRowCount()-rows.length-1, getRowCount()-1, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
    }

    public void clear() {
        if (rows.size() == 0)
            return;
        int oldSize = rows.size();
        rows.clear();
        fireEvent(new TableModelEvent(this, 0, oldSize-1, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE));
    }

    public void addRow(DataTableRow row) {
        rows.add(row);
        fireEvent(new TableModelEvent(this, getRowCount()-1, getRowCount()-1, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
    }

    private void fireEvent(TableModelEvent ev) {
        ListIterator<TableModelListener> it = modelListenerList.listIterator();
        while (it.hasNext())
            it.next().tableChanged(ev);
    }

    public DataTableRow getRow(int index) {
        return rows.get(index);
    }

    @Override
    public int getRowCount() {
        return rows.size();
    }

    @Override
    public int getColumnCount() {
        return columns.length;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return columns[columnIndex];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return Object.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return rows.get(rowIndex).getColumn(columnIndex);
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        throw new UnsupportedOperationException("Editing not supported");
    }

    @Override
    public void addTableModelListener(TableModelListener l) {
        modelListenerList.addLast(l);
    }

    @Override
    public void removeTableModelListener(TableModelListener l) {
        modelListenerList.remove(l);
    }



}